package level.editor.menu;

import java.io.File;
import java.io.FilenameFilter;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import core.Constants;

import level.editor.command.Command;
import level.editor.command.RequiresModule;
import level.editor.command.RequiresUpdate;
import level.editor.mediator.Module;
import level.editor.state.StateModule;
import level.state.StateReader;

public class StateOpenCommand extends Command implements RequiresUpdate,
		RequiresModule
{
	public StateOpenCommand()
	{
		super("StateModule");
	}

	public void execute(Module m)
	{
		StateModule module = (StateModule) m;
		String dirName = Constants.DEFAULT_SAVE_DIR;
		if (module.isModified())
		{
			int response = JOptionPane
					.showConfirmDialog(
							module.getWindow(),
							"The current file "
									+ " has not been saved. Do you want to save this file?",
							"Unsaved file", JOptionPane.YES_NO_CANCEL_OPTION,
							JOptionPane.WARNING_MESSAGE);
			if (response == JOptionPane.CANCEL_OPTION)
				return;
			else if (response == JOptionPane.YES_OPTION)
			{
				module.pushDownCommand(new StateSaveCommand());
				module.setModified(false);
			}
		}
		if (module.getState().getFile() != null)
			dirName = module.getState().getFile().getParent();
		FileFilter filter = new FileNameExtensionFilter("XML Filter", "xml");
		JFileChooser fc = new JFileChooser(dirName);
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fc.setFileFilter(filter);
		FilenameFilter filter2 = new FilenameFilter()
		{
			public boolean accept(File dir, String name)
			{
				return name.endsWith(".xml");
			}
		};
		int returnVal = fc.showOpenDialog(module.getWindow());

		if (returnVal != JFileChooser.APPROVE_OPTION)
		{
			return;
		}
		else
		{
			String[] fileNames = fc.getSelectedFile().getParentFile()
					.list((FilenameFilter) filter2);
			Boolean contains = false;
			if (fileNames.length != 0)
			{
				for (String fileName : fileNames)
				{
					if (fc.getSelectedFile().getName().equals(fileName))
					{
						contains = true;
					}
				}
				if (!contains)
				{
					JOptionPane.showMessageDialog(module.getWindow(),
							"File does not exist", "Error",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
			}
		}

		module.setModified(false);
		module.setState(StateReader.open(fc.getSelectedFile()));
		module.resetMemento();
	}
}
